package com.boot.main.utils;

import com.boot.main.config.WxConfig;
import com.wechat.pay.java.core.util.PemUtil;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Random;

public class WxPayUtil {
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();
    public static String getSign(String signatureStr) throws FileNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        File file = new File(WxConfig.privateKeyPath);
        InputStream in = new FileInputStream(file);
        PrivateKey merchatPrivateKey = PemUtil.loadPrivateKeyFromPath(WxConfig.privateKeyPath);
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(merchatPrivateKey);
        sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));
        return Base64Utils.encodeToString(sign.sign());
    }
    public static String generateNonceStr(){
        char[] nonceChars = new char[32];
        for(int i=0; i<nonceChars.length; ++i){
            nonceChars[i] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    public static long getCurrentTimestamp(){
        return System.currentTimeMillis()/1000;
    }
}
